const coupon = require('../../templates/coupon/coupon'),
      wxParse = require('../../templates/wxParse/wxParse');

Page({
  data: {
    height: 64, //header高度
    top: 0,     //标题图标距离顶部距离
    scrollH: 0, //滚动总高度
    opcity: 0,
    iconOpcity: 0.5,
    topMenu: [{
      icon: 'like-fill',
      text: '加入心愿',
      size: 26,
      color: 'red',
      tap: 'collecting'
    }, {
      icon: 'message',
      text: '消息',
      size: 26
    }, {
      icon: 'people',
      text: '我的',
      size: 26
    }, {
      icon: 'like',
      text: '心愿单',
      size: 26
    }, {
      icon: 'feedback',
      text: '我要反馈',
      size: 23
    }/*, {
      icon: 'share',
      text: '分享',
      size: 26
    }*/],
    tags: [
      {
        name: '新品',
        key: 'is_new',
        val: 1,
        type: 'high-green'
      },
      {
        name: '热门',
        key: 'is_hot',
        val: 1,
        type: 'danger'
      },
      {
        name: '优选',
        key: 'is_recommend',
        val: 1,
        type: 'high-blue'
      }
    ],
    menuShow: false,
    product: null,
    preferentialType: {
      1: '扣减',
      2: '折扣'
    },
    selectedPrice: 0,
    bannerIndex: 0,
    popupShow: false,
    value: 1,
    collected: false,
    curSelectNum: 0,     // 用户当前已选定的规格数
    //ongoing: false,    // 用于判断“立即购买”按钮是否可用
    btnText: '立即购买',  // 用于“立即购买”按钮的描述
  },
  onLoad: function (options) {
    let obj = wx.getMenuButtonBoundingClientRect();
    this.setData({
      id: options.id,
      width: obj.left,
      height: obj.top + obj.height + 8,
      top: obj.top + (obj.height - 32) / 2
    }, () => {
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            scrollH: res.windowWidth
          })
        }
      })
    });
  },
  onShow: async function () {
    // 调用previewImage后无需重新获取
    if (this.data.product) return;
    // 商品详情
    wx.util.request('', {
      body: {id: this.data.id}
    }).then(res => {
      let {
            defaultStock,
            defaultAttr,
          } = this.defaultData(res),
          canAddToCart = false,
          now = wx.time.curUnix(),
          ongoing = false, // 存在营销策略时，需根据product.marketing规则判断
          btnText = this.data.btnText;
      // 卡券信息处理
      res.canReceiveCoupon = coupon.format(res.canReceiveCoupon);
      // 只保留三条评价预览
      if (res.evaluate.length > 3) {
        let evaluate = [];
        for (let i = 0; i < 3; i++) {
          evaluate.push(res.evaluate[i]);
        }
        res.evaluate = evaluate;
      }
      if (res.comment_num > 10000) {
        res.comment_num = (res.comment_num / 10000).toFixed(2) + '万';
      }
      if (res.is_buy == 1 && res.status == 1 && res.stock > 0) {
        // 只有非营销商品或其PET == 1 || 3时方可走购物车渠道
        if (res.marketing.status != 1 && (res.point_exchange_type == 1 || res.point_exchange_type == 3)) {
          ongoing = true;
          canAddToCart = true;
        }
        // 营销优先级高于普通销售
        if (res.marketing && res.marketing.status == 1) {// 检查活动是否开启
          // 按钮描述
          if (now < res.marketing.start_time) {
            btnText = '即将开启';
          } else if (now >= res.marketing.end_time) {
            btnText = '您来晚了';
          } else {
            ongoing = true;
          }
          /*switch (res.marketing_type) {
            case 'group_buy': // 团购
              return;
              break;
            case 'discount':  // 限时折扣

              break;
            case 'wholesale': // 拼团
              return;
              break;
            case 'bargain': // 砍价
              return;
              break;
            case 'subscribe_buy': // 预购
              return;
              break;
          }*/
        }
      } else {
        if (res.status != 1) {
          btnText = '已下架';
        } else if (res.stock <= 0) {
          btnText = '已售罄';
        } else {
          btnText = '暂停购买';
        }
      }
      this.setData({
        product: res,
        needSelectNum: res.base_attribute_format.length,
        selectedAttr: defaultAttr,
        collected: res.myCollect,
        canAddToCart: canAddToCart,
        ongoing: ongoing,
        btnText: btnText,
        popThumb: res.picture,
        skuId: res.sku[0].id, // 默认
        stock: defaultStock,
        canSubmit: (res.is_attribute != 1),
        cartNum: Number(wx.getStorageSync('rf_member')['cart_num'])
      }, () => {
        this.calcPrice();
      });
      wxParse.wxParse('article', 'html', res.intro, this, 5);
    }).catch(err => {
      console.log(err)
    });
    if (await wx.user.hasLogin()) {
      // 未读消息数
      wx.util.request('message.unreadNum').then(res => {
        this.setData({
          messageNum: Number(res.count)
        });
      });
      // 默认收货地址
      wx.util.request('address.default').then(res => {
        if (res) {
          this.setData({
            address: res.address_name
          });
        }
      });
    }
  },
  //页面滚动执行方式
  onPageScroll(e) {
    let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop,
        opcity = scroll / this.data.scrollH;
    if (this.data.opcity >= 1 && opcity >= 1) {
      return;
    }
    this.setData({
      scroll: scroll,
      opcity: opcity,
      iconOpcity: 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
    })
  },
  onShareAppMessage: function () {
    let name = this.data.product.name;
    return {
      title: name.length > 46 ? name.substring(0, 45) + '...' : name
    }
  },
  labelItem(e) {
    //if (!this.data.ongoing) return;
    let attrIdx = e.currentTarget.dataset.attrindex,
        attrChildIdx = e.currentTarget.dataset.attrchildindex,
        product = this.data.product,
        sku = product.sku,
        attr = product.base_attribute_format,
        childs = attr[attrIdx].value,
        needSelectNum = this.data.needSelectNum,
        curSelectNum = 0,
        skuData = "",
        attrNames = "";
    // 取消该分类下的子栏目所有的选中状态
    for (let i in childs) {
      if (i == attrChildIdx) {
        childs[attrChildIdx].active = !childs[attrChildIdx].active;
      } else {
        childs[i].active = false;
      }
    }
    // 获取所有的选中规格尺寸数据
    for (let i = 0; i < needSelectNum; i++) {
      let child = attr[i].value;
      for (let item of child) {
        if (item.active) {
          curSelectNum++;
          skuData += skuData ? '-' + item.base_spec_value_id : item.base_spec_value_id;
          attrNames += `"${item.title}" `;
        }
      }
    }
    let {defaultAttr, defaultStock} = this.defaultData(product);
    let data = {
      product: product,
      skuData: skuData,
      curSelectNum: curSelectNum,
      canSubmit: false,
      selectedAttr: attrNames || defaultAttr
    };
    data.popThumb = product.picture;
    if (needSelectNum == curSelectNum) {
      for (let item of sku) {
        if (skuData == item.data) {
          if (item.picture) data.popThumb = item.picture;
          this.data.itemPrice = item.price;
          // 检查库存
          if (item.stock > 0) {
            data.skuId = item.id;
            data.stock = item.stock;
            data.buyNumMax = item.stock;
            data.canSubmit = true;
            data.btnText = '立即购买';
            // 商品sku限购检查，向前兼容
            if (item.max_buy && item.max_buy > 0) {
              data.buyNumMax = Number(item.max_buy);
            } else if (product.max_buy > 0) {
              data.buyNumMax = Number(product.max_buy);
            }
          } else {
            data.stock = 0;
            data.buyNumber = 0;
            data.buyNumMax = 0;
            data.canSubmit = false;
            data.btnText = '库存不足';
          }
          break;
        }
      }
    } else {
      data.stock = defaultStock;
    }
    this.setData(data, () => {
      this.calcPrice();
    });
  },
  defaultData: function (product) {
    product = product || this.data.product;
    let attrName = '';
    for (let item of product.base_attribute_format) {
      attrName += ' ' + item.title;
    }
    return {
      defaultAttr: '请选择' + attrName,
      defaultStock: product.stock
    }
  },
  calcPrice() {
    let data = this.data,
        buyNum = data.buyNumber,
        product = data.product,
        itemPrice = data.itemPrice || product.price,  // 已选规格的金额
        preferential = product.ladderPreferential,
        selectedPrice = 0,
        openDiscount = false, //(product.marketing.status == 1 && product.marketing_type == 'discount'),
        discount = product.marketing.discount || 100,
        reserve = product.marketing.decimal_reservation_number, // 折扣后的金额处理
        skuPrice = {
          min: product.minSkuPrice,
          max: product.maxSkuPrice
        };
    // 会员折扣
    if (product.memberDiscount && product.memberDiscount.discount) {
      itemPrice *= product.memberDiscount.discount / 100;
      itemPrice = this.priceFormat(itemPrice, product.memberDiscount.decimal_reservation_number);
    }
    // 如果商品存在SKU，在未选择明确属性前应展示最小与最大售价
    if (product.is_attribute == 1) {
      if (openDiscount) {
        for (let i in skuPrice) {
          let item = skuPrice[i];
          item = Math.round(item * discount) / 100;
          item = this.priceFormat(item, reserve);
          skuPrice[i] = item;
        }
      }
    }
    // 已选规格的折扣金额
    if (openDiscount) {
      itemPrice = Math.round(itemPrice * discount) / 100;
    }
    //  计算阶梯优惠
    if (data.curSelectNum == data.needSelectNum) {
      selectedPrice = itemPrice;
      for (let i in preferential) {
        let current = preferential[i];
        if (buyNum >= current.quantity) {
          if (current.type == '1' && (itemPrice - current.price > 0)) {
            selectedPrice = itemPrice - current.price;
          } else if (current.type == '2') {
            selectedPrice = itemPrice * (current.price / 100);
          }
        }
      }
    } else {
      selectedPrice = skuPrice.min + (skuPrice.max && skuPrice.min != skuPrice.max ? '-' + skuPrice.max : '');
    }
    this.setData({
      selectedPrice: isNaN(selectedPrice) ? selectedPrice : Number(selectedPrice).toFixed(2)
    });
  },
  priceFormat: function (price, formatType) {
    // -1：保留角和分；0：抹去角和分；1：抹去分
    if (formatType == 0) {
      price = Math.floor(price);
    } else if (formatType == 1) {
      price = Number(price.toFixed(1));
    }

    return price;
  },
  bannerChange: function (e) {
    this.setData({
      bannerIndex: e.detail.current
    });
  },
  previewImage: function (e) {
    let index = e.currentTarget.dataset.index;
    let banner = this.data.product.covers;
    wx.previewImage({
      current: banner[index],
      urls: banner
    });
  },
  back: function () {
    wx.navigateBack();
  },
  openMenu: function () {
    this.setData({
      menuShow: true
    });
  },
  closeMenu: function () {
    this.setData({
      menuShow: false
    });
  },
  showPopup: function (e) {
    this.setData({
      popupShow: true,
      showContent: e.currentTarget.dataset.type || 'sku'
    });
  },
  hidePopup: function () {
    this.setData({
      popupShow: false
    });
  },
  change: function (e) {
    this.setData({
      value: e.detail.value
    });
  },
  collecting: function () {
    let api = 'new', data = {
      body: {
        topic_id: this.data.product.id,
        topic_type: 'product'
      }
    };
    if (this.data.collected) {
      api = 'del';
      data = {query: `id=${this.data.collected.id}`};
    }
    wx.util.request(`common.collect.${api}`, data).then(res => {
      this.setData({
        collected: (api == 'new' ? res : null)
      });
    });
  },
  jump: function (e) {
    let type = e.currentTarget.dataset.type,
        func = 'navigateTo', url;
    switch (type) {
      case 'evaluate':
        if (this.data.product.comment_num < 1) {
          wx.util.toast('暂未收到评价');
        } else {
          url = `evaluate?pid=${this.data.product.id}&eid=${this.data.product.evaluateStat.id}`;
        }
        break;
      /*case 'service':
        url = '';
        break;*/
      case 'home':
        func = 'switchTab';
        url = '../index/index';
        break;
      case 'cart':
        func = 'switchTab';
        url = '../cart/index';
        break;
      case 'message':
        url = '../message/index';
        break;
      case 'people':
        func = 'switchTab';
        url = '../user/index';
        break;
      case 'like':
        url = '../user/collect';
        break;
      case 'feedback':
        url = '../feedback/new';
        break;
      default:
        wx.util.toast("功能开发中~");
        break;
    }
    if (url) {
      wx[func]({
        url: url,
      });
    }
  },
  addToCart: function () {
    if (this.data.curSelectNum != this.data.needSelectNum) {
      this.showPopup();
      return;
    }
    let num = this.data.value;
    wx.util.request('cart.new', {
      body: {
        sku_id: this.data.skuId,
        num: num
      }
    }).then(() => {
      let cartNum = this.data.cartNum + num;
      // 更新数量
      wx.setStorageSync('rf_member', {
        [`cart_num`]: cartNum
      });
      this.setData({
        cartNum: cartNum
      });
      wx.util.toast('已加入购物车');
      this.hidePopup();
    });
  },
  preview: function (e) {
    if (this.data.curSelectNum != this.data.needSelectNum) {
      this.showPopup(e);
      return;
    }
    if (!this.data.canSubmit) {
      this.showPopup(e);
      return;
    }
    this.hidePopup();
    wx.navigateTo({
      url: `../order/submit?type=buy_now&data=${JSON.stringify({sku_id: this.data.skuId,num: this.data.value})}`
    });
  },
  coupon: function () {
    if (this.data.product.canReceiveCoupon.length > 0) {
      this.setData({
        popupShow: true,
        showContent: 'coupon'
      });
    } else {
      wx.navigateTo({
        url: '../coupon/index'
      });
    }
  },
  receive: function (e) {
    coupon.receive(e.currentTarget.dataset.id);
  }
})